package com.domain.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.domain.common.Comments;
import com.domain.common.Const;
import com.domain.common.Result;
import com.domain.dao.*;
import com.domain.pojo.*;
import com.domain.service.BillService;
import com.domain.service.PushMessageService;
import com.domain.service.UsersService;
import com.domain.utils.ArithmeticUtil;
import com.domain.utils.DateUtils;
import com.domain.utils.NotNullUtils;
import com.domain.utils.UUIDUtils;
import com.domain.utils.wyyx.IMSndmsg;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class)
public class PushMessageServiceImpl implements PushMessageService {
    @Autowired
    private PushMessageMapper pushMessageMapper;

    @Autowired
    private UsersMapper usersMapper;


    @Autowired
    private PublishAcceptanceMapper publishAcceptanceMapper;

    @Autowired
    private UsersGroupInfoMapper usersGroupInfoMapper;

    @Autowired
    private UsersService usersService;

    @Autowired
    private PublishMapper publishMapper;


    @Autowired
    private BillService billService;

    @Autowired
    private UsersWalletMapper usersWalletMapper;


    /**
     * 获取用户推送列表
     *
     * @param userId
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true)
    public Result getPushMessageList(String userId, String pushType, String pageNum, String pageSize) {
        PageHelper.startPage(new Integer(pageNum), new Integer(pageSize));
        List<PushMessage> pushMessages = pushMessageMapper.selectByUsersId(userId, pushType);
        PageInfo pageInfo = new PageInfo(pushMessages);
        return Result.success("操作成功", pageInfo.getList());
    }

    /**
     * 添加推送帮忙消息
     *
     * @param pushUsersId     被推送者id
     * @param pushUsersSendId 推送者id
     * @param pushContent     推送消息
     * @param pushTitle       推送标题
     * @param spareOne        推送备用信息
     * @param spare_three     推送小分类
     * @param pushId          推送id
     * @return
     */
    @Override
    public Result addPublishiMessage(String pushUsersId, String pushUsersSendId, String pushContent, String pushTitle, String spareOne, String spare_three, String pushId, String userName) {
        //添加帮忙消息
        PushMessage pe = new PushMessage();
        pe.setId(pushId);
        pe.setPushTitle(pushTitle);
        pe.setSpareOne(spareOne);
        pe.setPushContent(pushContent);
        pe.setCreatTime(new Date());
        pe.setPushUsersSendId(pushUsersSendId);
        pe.setPushUsersId(pushUsersId);
        pe.setPushType(Const.PUBLISH_MESSAGE);
        pe.setSpareTwo(Const.MESSAGE_STATE);
        pe.setSpareThree(spare_three);
        pe.setPushIcons(userName);
        pushMessageMapper.insertSelective(pe);
        return Result.success();
    }

    /**
     * 添加推送系统消息
     *
     * @param pushUsersId
     * @param pushUsersSendId
     * @param pushContent
     * @param pushTitle
     * @param spareOne
     * @return
     */
    @Override
    public Result addSystemMessage(String pushUsersId, String pushUsersSendId, String pushContent, String pushTitle, String spareOne, String spareThree, String pushId, String userName) {
        //添加系统消息
        PushMessage pe = new PushMessage();
        pe.setId(pushId);
        pe.setPushTitle(pushTitle);
        pe.setSpareOne(spareOne);
        pe.setPushContent(pushContent);
        pe.setCreatTime(new Date());
        pe.setPushUsersSendId(pushUsersSendId);
        pe.setPushUsersId(pushUsersId);
        pe.setPushType(Const.SYSTEM_MESSAGE);
        pe.setSpareTwo(Const.MESSAGE_STATE);
        pe.setSpareThree(spareThree);
        pushMessageMapper.insertSelective(pe);
        return Result.success();
    }

    /**
     * 添加答谢通知
     *
     * @param pushUsersId
     * @param pushUsersSendId
     * @param pushContent
     * @param pushTitle
     * @param spareOne
     * @param spare_three
     * @param pushId
     * @return
     */
    @Override
    public Result addAcknowledgeMessage(String pushUsersId, String pushUsersSendId, String pushContent, String pushTitle, String spareOne, String spare_three, String pushId, String usersName) {
        //添加答谢通知
        PushMessage pe = new PushMessage();
        pe.setId(pushId);
        pe.setPushTitle(pushTitle);
        pe.setSpareOne(spareOne);
        pe.setPushContent(pushContent);
        pe.setCreatTime(new Date());
        pe.setPushUsersSendId(pushUsersSendId);
        pe.setPushUsersId(pushUsersId);
        pe.setPushType(Const.THANK_MESSAGE);
        pe.setSpareTwo(Const.MESSAGE_STATE);
        pe.setSpareThree(spare_three);
        pe.setPushIcons(usersName);
        pushMessageMapper.insertSelective(pe);
        return Result.success();
    }

    /**
     * 已读
     *
     * @param messageId
     * @return
     */
    @Override
    public Result changePushMessageState(String messageId) {
        PushMessage pe = new PushMessage();
        pe.setId(messageId);
        pe.setSpareTwo(Const.MESSAGE_STATE_YES);
        pe.setUpdateTime(new Date());
        pushMessageMapper.updateByPrimaryKeySelective(pe);
        return Result.success();
    }

    /**
     * 受理推送消息详情
     *
     * @param pushMessageId 推送消息id
     */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true)
    public Result acceptancePushDetail(String pushMessageId) throws Exception {
        Map<String, Object> maps = new HashMap<>();
        //获取推送详情
        PushMessage pe = pushMessageMapper.selectByPrimaryKey(pushMessageId);
        if (NotNullUtils.isNotNullObject(pe)) {
            //受理详情
            PublishAcceptance publishAcceptance = publishAcceptanceMapper.selectByPrimaryKey(pe.getSpareOne());
            //受理人详情
            Users users = usersMapper.selectByPrimaryKey(pe.getPushUsersSendId());
            //受理群组详情
            UsersGroupInfo usersGroupInfo = usersGroupInfoMapper.selectByCreatGroupAndAccpentId(publishAcceptance.getPublishId(), publishAcceptance.getUserId(), users.getId());
            if (NotNullUtils.isNotNullObject(usersGroupInfo)) {
                maps.put("groupID", usersGroupInfo.getGroupId());
            } else {
                maps.put("groupID", "");
            }
            maps.put("aUsersId", users.getId());
            maps.put("aUsersHead", users.getHeadImage());
            maps.put("aUsersName", users.getName());
            maps.put("aUsersGender", users.getGender());
            maps.put("aUsersBirthday", DateUtils.getAgeByBirthDay(users.getBirthday()));
            maps.put("aUsersCity", users.getCity());
            maps.put("aUsersIdyus", users.getIndustry());
            maps.put("publishUsersId", publishAcceptance.getUserId());
            maps.put("publishId", publishAcceptance.getPublishId());
            //帮转人id
            maps.put("helpUsersId", publishAcceptance.getSpareTwo());
            //人脉  publishAcceptance.getUserId()发布者id（用户id）  getAcceptanceId 受理者id  getSpareOne 帮转者id
            /* List<Map<String, Object>> list = usersService.getUsersHumanChain(publishAcceptance.getUserId(), users.getId(), publishAcceptance.getSpareOne(), "");*/
            /* maps.put("humanChain", list);*/
            /*       maps.put("friendsId",)*/
            maps.put("message", publishAcceptance.getAcceptanceMessage());
        }
        return Result.success("操作成功", maps);
    }

    /**
     * 创建讨论组
     *
     * @param usersId   用户id
     * @param friendsId 人脉id(逗号隔开)
     * @param accpId    受理人id
     * @param publishId 发布id
     * @return
     */
    @Override
    public Result creatGroup(String usersId, String friendsId, String accpId, String publishId, String helpUsersId) throws IOException {
        //发布者信息
        Users user = usersMapper.selectByPrimaryKey(usersId);
        //受理者信息
        Users useraccp = usersMapper.selectByPrimaryKey(accpId);
        //创建群时（群名称）
        String teamName = "" + user.getName() + "," + useraccp.getName() + "";
        //创建群聊时默认将受理人拉入群
        String members = "['" + accpId + "']";
        //拉人入群时的信息
        String msg = "{'msg':''}";
        //创建群组额外的参数
        Map<String, Object> maps = new HashMap<>();
        maps.put("publishId", publishId);
        if (NotNullUtils.isNotNullObject(helpUsersId)) {
            maps.put("helpUsersId", helpUsersId);
        } else {
            maps.put("helpUsersId", "");
        }
        String str = JSON.toJSONString(maps);
        //String costom = "[{'publishId':'" + publishId + "'},{'helpUsersId':'" + helpUsersId + "'}]";
        //群头像
        String icons = "" + user.getHeadImage() + "," + useraccp.getHeadImage() + "";
        String result = IMSndmsg.createTeam(teamName, user.getId(), members, "", "", msg, "0", "0", "1", "0", "0", icons, str);
        //创建群成功
        JSONObject jsObject = JSONObject.parseObject(result);
        if (jsObject.get("code").equals(200)) {
            //添加创建群信息
            String uuidgroup = UUIDUtils.getRandomUUID();
            UsersGroupInfo uf = new UsersGroupInfo();
            uf.setUsersId(usersId);
            uf.setGroupId(jsObject.get("tid").toString());
            uf.setCreatTime(new Date());
            uf.setGroupName(teamName);
            uf.setId(uuidgroup);
            uf.setPublishId(publishId);
            uf.setSpareOne(accpId);
            //将帮转人id传入其中
            uf.setSpareThree(helpUsersId);
            //群头像
            uf.setSpareTwo(icons);
            usersGroupInfoMapper.insertSelective(uf);
            //创建群成功（通知人脉链进群）
           /* String[] friendis = friendsId.split(",");
            for (String s : friendis) {
                //推送消息id
                String pushId = UUIDUtils.getRandomUUID();
                //拉人入群
                Jdpush.sendToAliasList(s, "" + useraccp.getName() + "接受了您人脉链中" + user.getName() + "的求助信息", "pushId", pushId, "pushType", Const.join_group, "bigTypeKey", Const.PUBLISH_MESSAGE, "邀请加入讨论组");
                //添加推送记录(sendUsersId 群号)
                addPublishiMessage(s, uuidgroup, "" + useraccp.getName() + "接受了您人脉链中" + user.getName() + "的求助信息,赶快加入讨论组帮助他们吧", "邀请加入讨论组", publishId, Const.join_group, pushId, "" + useraccp.getName() + "," + user.getName() + "");
            }*/
        }
        return Result.success(jsObject.get("tid"));
    }

    /**
     * 获取邀请加入讨论组详情
     *
     * @param pushMessageId
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true)
    public Result getJoinGroupDetail(String pushMessageId) {
        Map<String, Object> maps = new HashMap<>();
        //获取推送消息详情
        PushMessage pe = pushMessageMapper.selectByPrimaryKey(pushMessageId);
        //获取邀请人详情
        if (NotNullUtils.isNotNullObject(pe)) {
            //获取发布详情
            Publish publish = publishMapper.selectByPrimaryKey(pe.getSpareOne());
            //获取发布人详情
            Users users = usersMapper.selectByPrimaryKey(publish.getUserId());
            //获取群组详情
            UsersGroupInfo info = usersGroupInfoMapper.selectByPrimaryKey(pe.getPushUsersSendId());
            maps.put("usersId", users.getId());
            maps.put("usersHead", users.getHeadImage());
            maps.put("usersName", users.getName());
            maps.put("usersGender", users.getGender());
            maps.put("usersBirthday", DateUtils.getAgeByBirthDay(users.getBirthday()));
            maps.put("usersCity", users.getCity());
            maps.put("usersIdyus", users.getIndustry());
            maps.put("publishId", publish.getId());
            maps.put("tid", info.getGroupId());
            maps.put("content", pe.getPushContent());
            maps.put("usersHelpId", info.getSpareThree());
            //人脉  publishAcceptance.getUserId()发布者id（用户id）  getAcceptanceId 受理者id  getSpareOne 帮转者id
            List<Map<String, Object>> list = usersService.getUsersHumanChain(pe.getPushUsersId(), publish.getUserId(), info.getSpareThree(), "");
            maps.put("humanChain", list);
        }
        return Result.success("操作成功", maps);
    }

    /**
     * 获取用户未读得条数
     *
     * @param userId
     * @return
     */
    @Override
    public Result getMessageUnreadSize(String userId) {
        Map<String, Object> maps = new HashMap<>();
        //帮忙条数
        List<PushMessage> helps = pushMessageMapper.countHelp(userId);

        List<PushMessage> systems = pushMessageMapper.countSystems(userId);

        List<PushMessage> Acknowledges = pushMessageMapper.countAcknowledges(userId);

        if (helps.size() > 0) {
            maps.put("helps", "yes");
        } else {
            maps.put("helps", "no");
        }
        if (systems.size() > 0) {
            maps.put("systems", "yes");
        } else {
            maps.put("systems", "no");
        }
        if (Acknowledges.size() > 0) {
            maps.put("acknowledges", "yes");
        } else {
            maps.put("acknowledges", "no");
        }
        return Result.success(maps);
    }

    /**
     * 邀请加入讨论组
     *
     * @param usersId 用户id
     * @param groupId 群组id
     * @return
     */
    @Override
    public Result joinGroup(String usersId, String groupId) {
        //todo
        /* IMSndmsg.addTeam(groupId,)*/
        return null;
    }

    /**
     * 帮转红包领取红包
     *
     * @param pushMessageId
     * @return
     */
    @Override
    public Result getRedPacakge(String usersId, String pushMessageId) {
        PushMessage message = pushMessageMapper.selectByPrimaryKey(pushMessageId);
        //修改用户红包钱数
        UsersWallet usersWallet = usersWalletMapper.selectByUserId(usersId);
        BigDecimal m = ArithmeticUtil.add(usersWallet.getBalance().toString(), message.getSpareOne());
        usersWallet.setBalance(m);
        usersWallet.setUpdateTime(new Date());
        usersWalletMapper.updateByPrimaryKeySelective(usersWallet);
        //添加账单记录
        billService.addBill("", usersId, "拆开帮转红包", Comments.SERZERBAL_PUT, message.getSpareOne(), Const.RED_PACKAGE_ICONS);
        return Result.success();
    }

    /**
     * 答谢红包领取
     *
     * @param usersId
     * @param pushMessageId
     * @return
     */
    @Override
    public Result getAnserRedPacakge(String usersId, String pushMessageId) {
        PushMessage message = pushMessageMapper.selectByPrimaryKey(pushMessageId);
        //修改用户红包钱数
        UsersWallet usersWallet = usersWalletMapper.selectByUserId(usersId);
        BigDecimal m = ArithmeticUtil.add(usersWallet.getBalance().toString(), message.getSpareOne());
        usersWallet.setBalance(m);
        usersWallet.setUpdateTime(new Date());
        usersWalletMapper.updateByPrimaryKeySelective(usersWallet);
        Users users = usersMapper.selectByPrimaryKey(message.getPushUsersSendId());
        //添加账单记录
        billService.addBill("", usersId, "收到赏金-来自" + users.getName() + "", Comments.SERZERBAL_PUT, message.getSpareOne(), users.getHeadImage());
        return Result.success();
    }

   
}
